package models

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"user2/appconfig"
)

type User2 struct {
	gorm.Model
	Username string `gorm:"type:varchar(20)" json:"username"`
	Password string `gorm:"type:varchar(100)" json:"password"`
}

var DB *gorm.DB

func Init() {
	var err error
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	MysqlData := appconfig.Config.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		MysqlData.User, MysqlData.Password, MysqlData.Host, MysqlData.Port, MysqlData.Database)
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	DB.AutoMigrate(&User2{})
}
func (c *User2) Create() error {
	return DB.Create(&c).Error
}
func (c *User2) CreateLogin(username string) error {
	return DB.Where("username=?", username).Limit(1).Find(&c).Error
}
